<template>
  <div>
    <el-container class="container-box">
      <el-header class="container-header">
        <div class="container-header-title-box">
          <div class="icon-text">
            <span class="title icon-text">
              <el-icon class="text-primary margin0">
                <List />
              </el-icon>
              {{ getquestionbankbyid.name }}
            </span>
            <span class="container-header-detail-item">
              <!-- 题目数量：{{ getquestionbankbyid.questionquestionbank?.length }} -->
              <span v-if="questionCount.code"
                >代码题：{{ questionCount.code }}</span
              >
              <!-- &nbsp; &nbsp; -->
              <span v-if="questionCount.choice"
                >单选题：{{ questionCount.choice }}</span
              >
            </span>
          </div>
          <div v-if="user" class="copy">
            <el-button type="primary" plain size="default" @click="showCopy()">
              <el-icon :size="14">
                <DocumentCopy />
              </el-icon>
              &nbsp;复制为我的专题
            </el-button>
          </div>
        </div>
        <el-divider class="el-divider--horizontal"></el-divider>
        <div class="container-header-detail-box">
          <div class="container-header-detail-item">
            涵盖题目知识点：
            <el-button
              class="mb-1"
              type="primary"
              plain
              size="default"
              v-for="(vo, key) in label"
              :key="key"
              v-text="vo"
            >
            </el-button>
          </div>
          <div class="container-header-detail-item select-mode">
            <span>模式选择：</span>
            <span class="select-box">
              <el-tooltip placement="top">
                <template #content>
                  常用的练习模式，非编程题可以直接看到答案
                  <br />编程题可单独提交代码查看结果
                </template>
                <span @click="testclick(0)" :class="!istest ? 'selected' : ''"
                  >练习模式</span
                >
              </el-tooltip>
              <el-tooltip placement="top">
                <template #content
                  >题单将作为试卷整体提交，提交后会统一显示每道题是否正确</template
                >
                <span @click="testclick(1)" :class="istest ? 'selected' : ''"
                  >评测模式</span
                >
              </el-tooltip>
            </span>
            <el-button
              @click="toquestion(istest)"
              size="default"
              :style="{ fintSize: '18px' }"
              type="primary"
            >
              <el-icon>
                <EditPen />
              </el-icon>
              &nbsp;
              {{ !istest ? "进入练习" : "进入测评" }}
            </el-button>
          </div>
        </div>
      </el-header>
      <el-container>
        <el-main class="container-content">
          <div class="icon-text text-title">
            <!-- <b>专题题目</b> -->
          </div>
          <el-table
            :data="question"
            @row-click="rowClick"
            :row-class-name="tableRowClassName"
          >
            <template v-slot:empty>
              <el-empty
                image="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/image/ojSass-empty.png"
              />
            </template>
            <el-table-column width="60" prop="date" label="状态">
              <template #default="{ row }">
                <el-icon
                  :color="
                    Number(row.myACcount)
                      ? 'var(--color-cheng)'
                      : 'var(--color-43)'
                  "
                >
                  <Select v-if="Number(row.myACcount)" />
                  <CloseBold v-else-if="Number(row.myUNcount)" />
                  <SemiSelect v-else />
                </el-icon>
              </template>
            </el-table-column>
            <el-table-column
              prop="ID"
              width="100"
              label="题号"
            ></el-table-column>
            <el-table-column
              prop="type"
              width="80"
              label="题型"
            ></el-table-column>
            <el-table-column
              prop="name"
              show-overflow-tooltip
              width=""
              label="题目"
            ></el-table-column>
            <el-table-column prop="difficulty" width="" label="难度">
              <template #default="{ row, column }">
                <div
                  v-if="row.difficulty"
                  :class="`difficulty-${row.difficulty}`"
                >
                  {{ row.difficulty ? DATAdifficulty[row.difficulty] : "" }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="ACcount"
              width=""
              label="AC次数"
            ></el-table-column>
            <el-table-column
              prop="userquestioncount"
              width=""
              min-width="90"
              label="提交次数"
            ></el-table-column>
            <el-table-column prop="name" width="" label="AC率">
              <template #default="{ row, column }">
                <el-progress
                  :text-inside="true"
                  :stroke-width="18"
                  :percentage="getACRate(row)"
                  :color="customColors"
                />
              </template>
            </el-table-column>
            <el-table-column prop="questionlabel" width="" label="知识点">
              <template #default="{ row, column }">
                <el-tag
                  class="question-intable-label"
                  text
                  type="primary"
                  effect="plain"
                  size="small"
                  v-for="(vo, keys) in row.questionlabel"
                  v-text="getlabel.find((e) => e.ID === vo.labelid)?.name"
                  :key="`1-${keys}`"
                >
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-main>
        <el-aside class="container-aside" width="200px">
          <questionBankRank :ID="prop.ID"></questionBankRank>
        </el-aside>
      </el-container>
    </el-container>

    <div class="">
      <el-dialog v-model="dialogVisible" title="复制为我的专题" width="60vw">
        <template #header>
          <span class="icon-text el-dialog__header-title">
            <el-icon class="text-primary">
              <Guide />
            </el-icon>
            复制为我的专题
          </span>
        </template>
        <div>
          <el-input v-model="copyData.name">
            <template #prepend>编辑题单名称</template>
          </el-input>
        </div>
        <div>
          <h5
            :style="{
              fontSize: '18px',
              fontWeight: 700,
              marginTop: '24px',
            }"
          >
            请在下方选择需要复制的题单题目
          </h5>
        </div>
        <div :style="{}">
          <el-table
            ref="table"
            size="default"
            :data="getquestionbankbyid.questionquestionbank"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column
              prop="ID"
              width="100"
              label="题号"
            ></el-table-column>
            <el-table-column
              prop="question.name"
              label="题目"
            ></el-table-column>
          </el-table>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submit"
              >确定，并复制到我的题单</el-button
            >
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { DocumentCopy } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox, ElTable } from "element-plus";
import { uniq } from "underscore";
import { computed, onMounted, reactive, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { asynccopyquestionbank, asyncgetquestionbank } from "../../../api";
import { Iquestion, Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { DATAdifficulty } from "../../../index/data/data";
import questionBankRank from "./questionBankRank.vue";

// AC 率颜色
const customColors = [
  { color: "#e83828", percentage: 20 },
  { color: "#f0830ac", percentage: 40 },
  { color: "#82bd1c", percentage: 60 },
  { color: "#1ecbb4", percentage: 80 },
  { color: "#4683fa", percentage: 100 },
];
const prop = defineProps<{ ID: number }>();
const store = useStore(Storekey);
const router = useRouter();
const route = useRoute();
const dialogVisible = ref(false);
const getquestionbankbyid = reactive<Studycodemodel.Iquestionbank>({
  usertype: "public",
  questionquestionbank: [],
});
const copyData = reactive<Studycodemodel.Iquestionbank>({
  usertype: "public",
  questionquestionbank: [],
});
const getlabel = computed(() => {
  return store.state.label?.rows || [];
});
const user = computed(() => {
  return store.state.user;
});
const istest = computed(() => {
  return Boolean(Number(route.query.istest));
});
const label = computed(() => {
  return uniq(
    question.value
      ?.map((e) => e?.questionlabel)
      .map((e) =>
        e?.map((e) => getlabel.value.find((t) => t.ID === e.labelid)?.name)
      )
      .flat()
      .filter((e) => e) || []
  );
});
const question = computed(() => {
  return getquestionbankbyid.questionquestionbank?.map(
    ({ question }) => question
  );
});
const questionCount = computed(() => {
  let ret = { code: 0, choice: 0 };
  question.value?.forEach((e) => {
    if (e?.type === "代码") {
      ret.code++;
    }
    if (e?.type === "单选") {
      ret.choice++;
    }
  });
  return ret;
});

onMounted(() => {
  start();
});
async function start() {
  if (prop.ID) {
    try {
      const obj = await asyncgetquestionbank({ ID: prop.ID });
      // 同步数据
      Object.assign(getquestionbankbyid, obj);
    } catch (e) {
      ElMessage.error(e);
    }
  }
}

// AC率
function getACRate(row: Iquestion) {
  return row.userquestioncount
    ? Math.floor(
        (Number(row.ACcount || 0) / Number(row.userquestioncount)) * 100
      )
    : 0;
}

function tableRowClassName({
  row,
  rowIndex,
}: {
  row: Studycodemodel.Iquestionquestionbank;
  rowIndex: number;
}) {
  //把每一行的索引放进row
  (row as any).index = rowIndex;
  let className = "cursor-pointer";
  return className;
}
function rowClick(row: Studycodemodel.Iquestionquestionbank, column: any) {
  // `/test/${route.params.ID}/question/${k}` || `/question/${v?.ID}?questionbankid=${route.params.ID}`
  const clickROwIndex = (row as any).index;
  const name = istest.value ? `测评答题` : `题目`;
  const params = istest.value
    ? { ID: route.params.ID, index: clickROwIndex }
    : { ID: row?.ID };
  const query = istest.value ? {} : { questionbankid: route.params.ID };
  if (istest.value) {
    ElMessageBox.confirm("确定开始进行测评", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
    }).then((e) => {
      router.push({ name, params, query });
    });
  } else {
    router.push({ name, params, query });
  }
}

watch(
  () => prop.ID,
  (v) => {
    if (v) start();
  }
);

//////// old

function testclick(t: number) {
  router.push({
    name: "题库列表",
    params: { ID: route.params.ID },
    query: {
      istest: t,
    },
  });
}

function toquestion(t: boolean) {
  if (!user.value) {
    return ElMessage.error("请登录");
  }
  if (!question.value?.length) {
    ElMessage.error("此题单没有题目");
    return;
  }
  if (t) {
    ElMessageBox.confirm("确定开始进行测评", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
    }).then((e) => {
      router.push(`/test/${route.params.ID}/question/0`);
    });
  } else {
    router.push({
      name: "题目",
      params: { ID: question.value[0]?.ID },
      query: { questionbankid: route.params.ID },
    });
  }
}

// 复制题库
const table = ref<typeof ElTable>();
function showCopy() {
  if (!store.state.user) {
    return;
  }
  Object.assign(copyData, JSON.parse(JSON.stringify(getquestionbankbyid)));
  dialogVisible.value = true;
  setTimeout(() => {
    if (table.value) table.value.toggleAllSelection();
  }, 100);
}

async function submit() {
  if (!store.state.user) {
    return;
  }
  copyData.userid = store.state.user.ID;
  copyData.ID = undefined;
  await asynccopyquestionbank(copyData);
  dialogVisible.value = false;
  ElMessage.success("复制成功");
}

function handleSelectionChange(
  selection: Studycodemodel.Iquestionquestionbank[]
) {
  copyData.questionquestionbank = selection;
}
</script>

<style scoped>
.container-box {
  padding: var(--container-margin) 5% 0;
  margin: var(--container-margin) 0rem 0 0rem;
  /* 外边距 */
  --container-margin: 20px;
  --container-padding: 15px;
  --container-header-height: 24vh;
  --container-bg-color: #fff;
}

.container-header {
  /* height: var(--container-header-height);
  min-height: var(--container-header-height); */
  width: 100%;
  padding: var(--container-padding) calc(var(--container-margin) * 2);
  background: var(--container-bg-color);

  box-shadow: var(--container-box-shadow);
}

.container-header-title-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.container-header .title {
  color: #434343;
  font-weight: bold;
  font-size: 18px;
  margin-right: var(--container-margin);
}

.container-content {
  margin-top: var(--container-margin);
  margin-right: var(--container-margin);
  background: var(--container-bg-color);
  padding: var(--container-margin);
  min-width: 70%;
}

.container-aside {
  /* height: 150vh; */
  min-width: 25%;
  margin-top: var(--container-margin);
  background: var(--container-bg-color);
  padding: var(--container-margin);
}

.el-divider--horizontal {
  /* margin: var(--container-padding) 0 !important; */
}

.container-header-detail-box {
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  /* height: calc(var(--container-header-height) - 32px - var(--container-padding)*4); */
  height: auto;
}

.container-header-detail-item {
  line-height: 32px;
  /* height: 32px; */
}

.select-mode {
  margin-top: var(--container-margin);
}

.select-box {
  display: inline-block;
  /* width: 208px;
  height: 42px; */
  background: #f5f5f5;
  border-radius: 24px;
  text-align: center;
  margin-left: 15px;
  margin-right: 45px;
}

.select-box span {
  display: inline-block;
  width: 104px;
  height: 32px;
  border-radius: 24px;
  font-weight: bold;
  transition: all 0.3s;
  cursor: pointer;
}

.selected {
  background: var(--color-cheng);
  color: #ffffff;
}
</style>
